package com.jd.ymcc.mq;


import  static com.jd.ymcc.constants.MqConstants.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jd.ymcc.domain.MessageSms;
import com.jd.ymcc.dto.MessageSmsDto;
import com.jd.ymcc.dto.UserIdSmsDto;
import com.jd.ymcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup="message-sms-group",
        topic= COURSE_SMS_TOPIC,
        selectorExpression= COURSE_SMS_TAG
)
public class MessageSmsConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageSmsService messageSmsService;
    /**
     * 上架发送消息消费者
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        //1.获取消息体，判断是否为空
        byte[] body = messageExt.getBody();
        if (body==null || body.length==0){
            return;
        }
        //2.转化为jsno格式
        MessageSmsDto messageSmsDto = JSONObject.parseObject(new String(body, StandardCharsets.UTF_8), MessageSmsDto.class);
        //3.保存到数据库
        saveMessageSms(messageSmsDto);
        //4.发送短信
        log.info("发送短信成功！");
    }

    private void saveMessageSms(MessageSmsDto messageSmsDto) {
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(messageSmsDto.getTitle());
        messageSms.setContent(messageSmsDto.getContent());
        messageSms.setSendTime(new Date());
        List<UserIdSmsDto> users = messageSmsDto.getUsers();
        users.forEach(e->{
            messageSms.setUserId(e.getUserId());
            messageSmsService.insert(messageSms);
        });

    }
}
